#include "car.h"

car::car(){
    carNum="";
    carType="";
    color="";
    allTime=QDateTime::currentDateTime();
    carMap=nullptr;
};

car::car(QString cn,QString ct,QString co,QString at,QMap<QString,car>* cm) {
    //为私有成员赋值
    carNum=cn;
    carType=ct;
    color=co;
    allTime=QDateTime::fromString(at,"yyyy-MM-dd-hh:mm:ss");
    carMap=cm;
}

bool car::addCar(QString cn, QString ct, QString co, QString at)
{
    //存在该车牌号的汽车,取消添加汽车并返回false
    if(!(*carMap)[cn].carNum.isEmpty())return false;

    //不存在该车牌号的汽车,则添加
    car c(cn,ct,co,at,carMap);
    (*carMap)[cn]=c;
    return true;
}

bool car::delCar(QString cn)
{
    //不存在该车牌号的汽车,取消删除汽车并返回false
    if((*carMap)[cn].carNum.isEmpty())return false;

    //存在该车牌号的汽车,则删除
    (*carMap).remove(cn);
    return true;
}

car car::findCar(QString cn)
{
    return (*carMap)[cn];
}

bool car::modCar(QString cn, QString ct, QString co, QString at)
{
    //如果不存在该车牌号的汽车则返回false
    if((*carMap)[cn].carNum.isEmpty())return false;

    //如果存在该车牌号的汽车则修改其信息
    (*carMap)[cn].carType=ct;
    (*carMap)[cn].color=co;
    (*carMap)[cn].allTime=QDateTime::fromString(at,"yyyy-MM-dd-hh:mm:ss");
    return true;
}

long long car::timeAmount()
{
    return QDateTime::currentDateTime().secsTo(allTime);
}

bool car::saveInfo()
{
    QFile file(g_carFileName);
    if(file.open(QIODevice::WriteOnly)){//如果car数据文件打开成功则写入文件并返回true
        for(auto i=carMap->begin();i!=carMap->end();++i){
            QString input;
            if(!i.value().carNum.isEmpty()){
                if(i!=carMap->begin())input+="\n";
                input+=i.value().carNum;
                input+="\t"+i.value().carType;
                input+="\t"+i.value().color;
                input+=i.value().allTime.toString("yyyy-MM-dd-hh:mm:ss");
            }
        }
        file.close();
        return true;
    }
    //如果car数据文件打开失败则返回false
    return false;
}

QString car::getCarNum()
{
    return carNum;
}

QString car::getCarType()
{
    return carType;
}

QString car::getColor()
{
    return color;
}

QDateTime car::getAllTime()
{
    return allTime;
}
